package com.oobi.showlive.datastore.service.reg;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.JDOCanRetryException;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.oobi.showlive.datastore.data.conn.PMF;
import com.oobi.showlive.datastore.data.reg.Registration;

public class Register extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		    PersistenceManager pm = PMF.get().getPersistenceManager();
			resp.setContentType("text/plain");
		    PrintWriter out = resp.getWriter();
			
			 // Get the user's name and password
		    String name = req.getParameter("name");
		    String passwd = req.getParameter("passwd");
		    
		    if(notEmpty(name) && notEmpty(passwd)) {
		    	Registration r = new Registration(name, passwd);
		        try {
		        	if(!isRegistrationExist(pm,r)) {
		        	
		        		pm.makePersistent(r);
		        		resp.setStatus(HttpServletResponse.SC_OK);
		        		out.write("Registration Successful");
		                return;
		        	} else {
		        		throw new Exception("Duplicate Entry");
		        	}
		        } catch(Exception e) {
		        	resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
		        } finally {
		            pm.close();
		        }
		    } else {
		    	resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
		    }
	}
	
	private boolean isRegistrationExist(PersistenceManager pm, Registration r) {
		try{
		  pm.getObjectById(Registration.class,r.getKey());
		  return true;
		}catch(JDOObjectNotFoundException objnfe){
			return false;
		}
	}
	
	 protected boolean notEmpty(String str) {
		    if(str!=null && !"".equals(str) )
		    	return true;  
		    else 
		    	return false;
      }
}
